package org.sbi.satvik.model;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.sbi.satvik.beans.SatvikFromBean;
import org.sbi.satvik.utility.HibernateUtil;

import com.google.gson.Gson;

public class SaveFormDataModel {
	
	
	
	
	public static  Date date = new Date();
	
	
	
	public static String saveFormData(String dataArrString){
		
		String retrunString  = ""; 
		SatvikFromBean satvikFromBean =new Gson().fromJson(dataArrString, SatvikFromBean.class);
		System.out.println(satvikFromBean.getSex());
		DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		
		
		System.out.println("date.........."+dateFormat.format(date));
		
		satvikFromBean.setEntryDate(dateFormat.format(date));
		
		/**
		 * FOR GENRATION OF UNIQUE ID OF USER
		 */
		Random randomNum = new Random();
		String responceCode="";
        for(int i = 0; i<4; i++){
        	responceCode+=randomNum.nextInt(4);
        	
        }
        satvikFromBean.setUniqueDataId(satvikFromBean.getApplicant_name()+responceCode);
        
		/**
		 * END OF UNIQUE ID
		 */
        
        satvikFromBean.setHiddenFlag(1);
        
        
        
        /**
         * hibernate operation for saving data
         */
		Session session = HibernateUtil.openSession();
		
		Transaction tx = null;	
		 try {
			 tx = session.getTransaction();
			 tx.begin();
			 session.saveOrUpdate(satvikFromBean);		
			 tx.commit();
		 } catch (Exception e) {
			 if (tx != null) {
				 tx.rollback();
			 }
			 retrunString = "Error";
			 e.printStackTrace();
		 } finally {
			 session.close();
		 }	
		/**
		 * End data Save
		 */
		
		 retrunString = "savedSuccess";
		
		
		return retrunString;
	}
}
